#include <stddef.h>
#include "string.h"


#include "libavformat/avformat.h"
#include "libavutil/imgutils.h"
#include "libavcodec/avcodec.h"
#include "libavdevice/avdevice.h"

int main(int argc, char **argv) {
    const char *infileName1 = argv[0];

    av_log_set_level(AV_LOG_DEBUG);

    const char *infileName = "../../1.mp4";
    const char *outfileName = "../../000out/1.aac";

    AVFormatContext *avFormatContext = NULL;
    int ret =
            avformat_open_input(
            &avFormatContext,
            infileName,
            NULL,
            NULL
    );

    if (ret != 0) {
        av_log(NULL, AV_LOG_ERROR, "open input file:%s failed: %s\n", infileName, av_err2str(ret));
        return -1;
    }

    avformat_find_stream_info(avFormatContext, NULL);

    int audioIndex =av_find_best_stream(avFormatContext, AVMEDIA_TYPE_AUDIO, -1, -3, NULL, 0);
    av_log(NULL, AV_LOG_INFO, "av_find_best_stream返回结果: %d\n", audioIndex);

    AVPacket *avPacket = malloc(sizeof(AVPacket));
    av_init_packet(avPacket);

    FILE *pFile = fopen(outfileName, "wb");
    while (av_read_frame(avFormatContext, avPacket) < 0) {
        if (avPacket->stream_index == audioIndex) {
            fwrite(avPacket->data, 1, avPacket->size, pFile);
        }
    }


    fclose(pFile);
    avformat_close_input(&avFormatContext);


    return 0;
}
